package com.btks.mapreduce.mapjoin;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yiwannuofulasi
 * @description TODO
 * @date 2023/3/27 17:04
 * Copyright (c) 2023/3/27 by yiwannuofulasi yiwannuofulasi@163.com, by 新疆兵团勘测设计院（集团）有限公司 All Rights Reserved.
 */
public class MapJoinMapper extends Mapper<LongWritable, Text,Text, NullWritable> {

    private Map<String, String> pdMap = new HashMap<>();
    private Text text = new Text();

    @Override
    protected void setup(Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {

        // 根据缓存文件得到小表数据pd.txt
        URI[] cacheFiles = context.getCacheFiles();
        Path path = new Path(cacheFiles[0]);

        // 获取文件系统对象，并开流
        FileSystem fs = FileSystem.get(context.getConfiguration());
        FSDataInputStream fis = fs.open(path);

        // 通过包装流转换reader便于按行读取
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        // 逐行读取，按行处理
        String line;
        while (StringUtils.isNotEmpty(line=reader.readLine())){
            String[] split = line.split("\t");
            pdMap.put(split[0],split[1]);
        }
        IOUtils.closeStream(reader);
    }

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
        // 读取大表数据
        String[] split = value.toString().split("\t");
        String pname = pdMap.get(split[1]);
        text.set(split[0] + "\t" + pname +"\t"+split[2]);
        context.write(text,NullWritable.get());
    }
}
